/**
 * 添加或者修改页面
 */
var TDispatchInfoDlg = {
    data: {
        mileageTraveled: ""
    }
};
/**
 * 添加或者修改页面
 */
var BasicCarrierInfoDlg = {
    data: {
        carrierId: "",
        carrierName: "",
    }
};
var submit = 2;
layui.use(['form', 'admin', 'ax','laydate'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;

    //让当前iframe弹层高度适应
    admin.iframeAuto();

    //获取详情信息，填充表单
    var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/detailBydispatchNumber?dispatchNumber=" + Feng.getUrlParam("dispatchNumber"));
    var result = ajax.start();
	if(result.data.loadingType == "自装"){
		$("#loadingNumbers").val("")
		$("#loadingNumberlabel").hide()
		$("#loadingNumberdiv").hide()
	}
    form.val('tDispatchForm', result.data);
	$("#loadingNumbers").val(result.data.loadingNumber)
    //执行一个laydate实例
    laydate.render({
      elem: '#startDate' //指定元素
        	,value:new Date()
            ,min:0
    });
    //执行一个laydate实例
    laydate.render({
      elem: '#yaoqiushijian' //指定元素
        	,type:"datetime"
    });
    //执行一个laydate实例
    laydate.render({
      elem: '#daodashijian' //指定元素
        	,type:"datetime"
    });

    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        let _data = data;
        var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/getTs", function (data) {
            if (data.success) {
                save(_data);
            } else { // 检查是否为400状态码（线路必须设置的情况）
                if (data.code === 400) {
                    // 线路未设置，禁用提交按钮并显示错误信息
                    $('button[lay-submit]').attr('disabled', 'disabled');
                    layer.alert(data.message, {
                        title: '错误',
                        icon: 2 // 错误图标
                    });
                } else {
                    // 其他情况弹出确认框
                    let ts = layer.open({
                        title: '提示',
                        content: data.message,
                        btn: ['确定', '取消'], // 自定义按钮名称
                        yes: function(index, layero) {
                            // 触发确定按钮的回调函数
                            layer.close(index);
                            save(_data);
                        },
                        btn2: function(index, layero) {
                            // 触发取消按钮的回调函数
                            layer.close(index);
                        }
                    });
                }
            }
        }, function (data) {
            // Feng.error("更新失败！" + data.responseJSON.message)
            // 错误回调函数
            if (data.status === 400) {
                // 线路必须设置的情况，禁用提交按钮
                $('button[lay-submit]').attr('disabled', 'disabled');
                layer.alert("不能操作！" + data.responseJSON.message, {
                    title: '错误',
                    icon: 2
                });
            } else {
                Feng.error("更新失败！" + data.responseJSON.message);
            }
        });
        $('button[lay-submit]').attr('disabled', 'disabled');
        ajax.set(data.field);
        ajax.start();
        return false;
    });


    function save(data){
        var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/editItem", function (data) {
            if (data.success) {
                parent.submit = 1
                if (data.message !=null &&data.message!='') {
                    var msg2 =  layer.open({
                        title: '提示' ,
                        content: data.message,
                        btn: ['确定'],
                        yes: function (){
                            layer.close(msg2);
                            var Index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(Index);
                        }
                    });
                } else {
                    Feng.success("提交成功!");
                    var Index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(Index);
                }
            } else {
                Feng.error("提交失败！"+data.message);
            }
        }, function (data) {
            Feng.error("更新失败！" + data.responseJSON.message)
        });
        data.field.loadingNumbers = data.field.loadingNumbers.replace('，',',')
        data.field.loadingNumbers = data.field.loadingNumbers.replace('.',',')
        data.field.loadingNumbers = data.field.loadingNumbers.replace('。',',')
        ajax.set(data.field);
        ajax.start();
    }
    
    /*form.on('select(chengyunleixing)',function(){
		var settlement = $("#chengyunleixing").val();
		if(settlement == "" || settlement == null){
			$("#payee").val("");
			$("#bank").val("");
			$("#bankAddress").val("");
			$("#bankAccount").val("");
			$("#bankNo").val("");
		} else {
	    	$.ajax({
	    		url:Feng.ctxPath + '/orderTransportDispatch/getsettlement',
	    	    dataType:"json",   //返回格式为json
	    	    async: false,
	    	    data:{"chengyunleixing":$("#chengyunleixing").val(),"carrierId":$("#carrierId").val(),"carId":$("#carId").val()},    //参数值
	    	    type:"post",   //请求方式
	    	    success:function(data){
	    	        if(data.data != null){
						$("#payee").val(data.data.payee);
						$("#bank").val(data.data.bank);
						$("#bankAddress").val(data.data.bankAddress);
						$("#bankAccount").val(data.data.bankAccount);
						$("#bankNo").val(data.data.bankNo);
						//两种设置select选择值都可以
						$('#cycle').val(data.data.cycle);
						//$('#cycle').find("option[value="+data.data.cycle+"]").attr("selected",true);
						$('#oilCardNumber').val(data.data.oilCardNumber);
						form.render('select') //再次渲染
	    	        }
	    	    }
	    	});
		}
    });*/
    
    form.on('select(loadingType)',function(){
		var loadingType = $("#loadingType").val();
		if(loadingType == "仓库"){
			$("#loadingNumberdiv").show()
		} 
		if(loadingType == "自装"){
			$("#loadingNumbers").val("")
			$("#loadingNumberlabel").hide()
			$("#loadingNumberdiv").hide()
		} 
    });

    // 选择配送设置事件
    $('#transportSet').click(function () {
        layer.open({
            type: 2,
            title: '配送设置',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/transportReceipt/toTransportSet?dispatchNumber='+Feng.getUrlParam("dispatchNumber"),
            end: function () {
            }
        });
    });

    // 选择计算里程事件
    $('#count').click(function () {
		submit = 2
        layer.open({
            type: 2,
            title: '计算里程',
            area: ['900px', '500px'],
            anim: 5,
            content: Feng.ctxPath + '/transportReceipt/toCount?dispatchNumber='+Feng.getUrlParam("dispatchNumber"),
            end: function () {
				if(submit == 1){
            		$("#mileageTraveled").val(TDispatchInfoDlg.data.mileageTraveled);
                    console.log(TDispatchInfoDlg.data.mileageTraveled + "aaa")
				}
            }
        });
    });

    // 选择计算费用事件
    $('#countCost').click(function () {
        var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/countCost2?dispatchNumber="+Feng.getUrlParam("dispatchNumber")+"&loadingType="+$("#loadingType").val()+"&mileageTraveled="+$("#mileageTraveled").val(), function (data) {
    		if (data.success) {
                Feng.success("计算成功!");
                console.log(data);
                $("#consultMoney").val(data.data.consultMoney);
                $("#freightMoney").val(data.data.freightMoney);
                $("#loadingMoney").val(data.data.loadingMoney);
            } else {
                Feng.error("计算失败！"+data.message);
			}
        }, function (data) {
            Feng.error("计算失败!" + data.responseJSON.message + "!");
        });
        ajax.start();
    });

    // 选择费用明细事件
    $('#costDetail').click(function () {
        layer.open({
            type: 2,
            title: '费用信息',
            area: ['900px', '500px'],
            anim: 5,
            content: Feng.ctxPath + '/transportCost?dispatchNumber=' + Feng.getUrlParam("dispatchNumber"),
        });
    });
    
    //点击承运商
    $("#carrierName").click(function(){
        layer.open({
            type: 2,
            title: '选择承运商',
            area: ['900px', '550px'],
            content: Feng.ctxPath + '/basicLinePrice/toCarrierName',
            end: function () {
				if(BasicCarrierInfoDlg.data.carrierId != null && BasicCarrierInfoDlg.data.carrierId != ''){
	                $("#carrierId").val(BasicCarrierInfoDlg.data.carrierId);
	                $("#carrierName").val(BasicCarrierInfoDlg.data.carrierName);
				}
            }
        });
    });

    //返回按钮
    $("#backupPage").click(function () {
    	var Index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(Index);
    });

});